<?php

namespace backend;

class Controller_Post extends \Controller_Template
{
    public function before()
    {
        parent::before();
    }
    
    public function action_create()
    {
        if(\Auth\Auth::check())
        {
            if(\Fuel\Core\Input::method() == "POST")
            {
                $post = \Model_Post::forge(\Fuel\Core\Input::post());
                $post->user_id = \Auth\Auth::instance()->get_user_id()[1];
                $post->slug = $this->createSlug($post->title);
                $val  = \Model_Post::register_create("create", \Fuel\Core\Input::post());
                if($val->run())
                {
                    // add university
                    if(\Fuel\Core\Input::post("university_id") == "" && \Fuel\Core\Input::post("university") != "")
                    {
                        $university = \Model_University::forge();
                        $university->name = \Fuel\Core\Input::post("university");
                        $university->category_id = 1;
                        $university->city_id = 1;
                        $university->slug = $this->createSlug(\Fuel\Core\Input::post('university'));
                        if($university && $university->save())
                        {
                            $post->university_id = $university->id;
                        }
                        else
                        {
                            \Fuel\Core\Session::set_flash("error", "Đã xảy ra lỗi bạn hãy thực hiện lại");
                        }
                    }
                    
                    // add ccourse
                    if(\Fuel\Core\Input::post('course_id') == '' && \Fuel\Core\Input::post('course') != '')
                    {
                        $course = \Model_Course::forge();
                        $course->name = \Fuel\Core\Input::post('course');
                        $course->slug = $this->createSlug(\Fuel\Core\Input::post('course'));
                        if($course && $course->save())
                        {
                            $post->course_id = $course->id;
                        }
                        else
                        {
                            \Fuel\Core\Session::set_flash('error', "Đã có lỗi, bạn hãy thực hiện lại");
                        }
                    }
                    
                    // add teacher
                    if(\Fuel\Core\Input::post('teacher_id') == '' && \Fuel\Core\Input::post('teacher') != '')
                    {
                        $teacher = \Model_Teacher::forge();
                        $teacher->name = \Fuel\Core\Input::post('teacher');
                        $teacher->slug = $this->createSlug(\Fuel\Core\Input::post('teacher'));
                        if($teacher && $teacher->save())
                        {
                            $post->teacher_id = $teacher->id;
                        }
                        else
                        {
                            \Fuel\Core\Session::set_flash('error', 'Đã có lỗi, bạn hãy thực hiện lại');
                        }
                    }
                    
                    if($post && $post->save())
                    {
                        \Fuel\Core\Session::set_flash("success", "Bạn đăng tài liệu thành công");
                        \Fuel\Core\Response::redirect("backend/post/admin");
                    }
                    else
                    {
                        \Fuel\Core\Session::set_flash("error", "Đăng tài liệu không thành công. Bạn hãy thực hiện lại.");
                    }
                }
                else
                {
                    $data["valid"] = $val->error();
                }
            }
            $data['page_title'] = "Đăng tài liệu";
            $data['university'] = $this->getListTableDB('Model_University', 'id', 'name', 'Chọn trường');
            $data['course'] = $this->getListTableDB('Model_Course', 'id', 'name', 'Chọn môn học');
            $data['teacher'] = $this->getListTableDB('Model_Teacher', 'id', 'name', 'Chọn giảng viên');
            $data['type'] = $this->getListTableDB('Model_Type', 'id', 'name', 'Chọn thể loại');
            $data['year'] = $this->getYear();
            $this->template->title = "Đăng tài liệu";
            $this->template->content = \Fuel\Core\View::forge('post/create', $data);
        }
        else
        {
            \Fuel\Core\Response::redirect('home/login');
        }
    }
    
    public function action_admin()
    {
        $data['posts'] = \Model_Post::find('all', array(
            'order' => "id DESC",
        ));
        $data['page_title'] = "Quản lý tài liệu";
        $this->template->title = "Quản lý tài liệu";
        $this->template->content = \Fuel\Core\View::forge('post/admin', $data);
    }
    
    public function action_list()
    {
        $data['page_title'] = "Danh sách tài liệu";
        $this->template->title = "Danh sách tài liệu";
        $this->template->content = \Fuel\Core\View::forge('post/list', $data);
    }
    
    public function action_update()
    {
        $data['page_title'] = "Cập nhật thông tin tài liệu";
        $this->template->title = "Cập nhật tài liệu";
        $this->template->content = \Fuel\Core\View::forge('post/update', $data);
    }
    
    public function action_delete()
    {
        $data['page_title'] = "Xóa tài liệu";
        $this->template->title = "Xóa tài liệu";
        $this->template->content = \Fuel\Core\View::forge('post/delete', $data);
    }
    
    protected function getListTableDB($model, $field1, $field2, $default)
    {
        $data = array('' => $default);
        $list = $model::find('all', array(
            'select' => array($field1, $field2),
            'order_by' => array(
                $field2 => 'asc',
            ),
        ));
        foreach($list as $item)
        {
            $data[$item[$field1]] = $item[$field2];
        }
        return $data;
    }
    
    public function getYear()
    {
        $arr = array();
        $year_cur = date('Y');
        for($i = $year_cur; $i >= 2008; $i--)
        {
            $arr[$i] = $i;
        }
        return $arr;
    }
    
    public function createSlug($string) {
        $a = array('À','Á', 'Ả', 'Ạ', 'Ã', 'Ă', 'Ắ', 'Ằ', 'Ẳ', 'Ặ', 'Ẵ', 'Â','Ấ','Ầ','Ẩ','Ậ','Ẫ','Đ','È','É','Ẻ','Ẹ','Ẽ','Ê','Ề','Ế','Ệ','Ể','Ễ','Ì','Í','Ỉ','Ị','Ĩ','Ò','Ó','Ỏ','Ọ','Õ','Ô','Ố','Ồ','Ổ','Ộ','Ỗ','Ơ','Ớ','Ờ','Ợ','Ở','Ỡ','Ù','Ú','Ủ','Ụ','Ũ','Ư','Ứ','Ừ','Ự','Ử','Ữ','Ý','Ỳ','Ỷ','Ỵ','Ỹ','á','à','ả','ạ','ã','ă','ắ','ằ','ặ','ẳ','ẵ','ấ','â','ầ','ậ','ẩ','ẫ','đ','è','é','ẹ','ẻ','ẽ','ê','ế','ề','ệ','ể','ễ','ì','í','ị','ỉ','ĩ','ò','ó','ỏ','ọ','õ','ô','ồ','ố','ổ','ộ','ỗ','ơ','ớ','ờ','ợ','ở','ỡ','ù','ú','ụ','ủ','ũ','ư','ừ','ứ','ự','ử','ữ','ỳ','ý','ỷ','ỵ','ỹ','Ä','Å','Æ','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö','Ø','Ù','Ú','Û','Ü','Ý','ß','à','á','â','ã','ä','å','æ','ç','è','é','ê','ë','ì','í','î','ï','ñ','ò','ó','ô','õ','ö','ø','ù','ú','û','ü','ý','ÿ','Ā','ā','Ă','ă','Ą','ą','Ć','ć','Ĉ','ĉ','Ċ','ċ','Č','č','Ď','ď','Đ','đ','Ē','ē','Ĕ','ĕ','Ė','ė','Ę','ę','Ě','ě','Ĝ','ĝ','Ğ','ğ','Ġ','ġ','Ģ','ģ','Ĥ','ĥ','Ħ','ħ','Ĩ','ĩ','Ī','ī','Ĭ','ĭ','Į','į','İ','ı','Ĳ','ĳ','Ĵ','ĵ','Ķ','ķ','Ĺ','ĺ','Ļ','ļ','Ľ','ľ','Ŀ','ŀ','Ł','ł','Ń','ń','Ņ','ņ','Ň','ň','ŉ','Ō','ō','Ŏ','ŏ','Ő','ő','Œ','œ','Ŕ','ŕ','Ŗ','ŗ','Ř','ř','Ś','ś','Ŝ','ŝ','Ş','ş','Š','š','Ţ','ţ','Ť','ť','Ŧ','ŧ','Ũ','ũ','Ū','ū','Ŭ','ŭ','Ů','ů','Ű','ű','Ų','ų','Ŵ','ŵ','Ŷ','ŷ','Ÿ','Ź','ź','Ż','ż','Ž','ž','ſ','ƒ','Ơ','ơ','Ư','ư','Ǎ','ǎ','Ǐ','ǐ','Ǒ','ǒ','Ǔ','ǔ','Ǖ','ǖ','Ǘ','ǘ','Ǚ','ǚ','Ǜ','ǜ','Ǻ','ǻ','Ǽ','ǽ','Ǿ','ǿ');
        $b = array('A','A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A','A','A','A','A','A','D','E','E','E','E','E','E','E','E','E','E','E','I','I','I','I','I','O','O','O','O','O','O','O','O','O','O','O','O','O','O','O','O','O','U','U','U','U','U','U','U','U','U','U','U','Y','Y','Y','Y','Y','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','d','e','e','e','e','e','e','e','e','e','e','e','i','i','i','i','i','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','o','u','u','u','u','u','u','u','u','u','u','u','y','y','y','y','y','A','A','AE','C','E','E','E','E','I','I','I','I','D','N','O','O','O','O','O','O','U','U','U','U','Y','s','a','a','a','a','a','a','ae','c','e','e','e','e','i','i','i','i','n','o','o','o','o','o','o','u','u','u','u','y','y','A','a','A','a','A','a','C','c','C','c','C','c','C','c','D','d','D','d','E','e','E','e','E','e','E','e','E','e','G','g','G','g','G','g','G','g','H','h','H','h','I','i','I','i','I','i','I','i','I','i','IJ','ij','J','j','K','k','L','l','L','l','L','l','L','l','l','l','N','n','N','n','N','n','n','O','o','O','o','O','o','OE','oe','R','r','R','r','R','r','S','s','S','s','S','s','S','s','T','t','T','t','T','t','U','u','U','u','U','u','U','u','U','u','U','u','W','w','Y','y','Y','Z','z','Z','z','Z','z','s','f','O','o','U','u','A','a','I','i','O','o','U','u','U','u','U','u','U','u','U','u','A','a','AE','ae','O','o');
        $string = str_replace($a, $b, $string);
        $string = preg_replace( '/[«»“”!?,.]+/', '', $string );
        return strtolower(preg_replace(array('/[^a-zA-Z0-9 -]/', '/[ -]+/', '/^-|-$/'), array('', '-', ''), $string));
    }
}